from machine import Pin
from device import Device

class LED(Device):
    """LED设备"""
    
    def __init__(self, name, pin_number=10):
        super().__init__(name)
        self.pin_number = pin_number
        self.led = None
    
    def initialize(self):
        """初始化LED"""
        try:
            self.led = Pin(self.pin_number, Pin.OUT)
            # 初始状态: 关闭 (1表示关闭)
            self.led.value(1)
            self.initialized = True
            return True
        except Exception as e:
            print(f"LED初始化失败: {e}")
            return False
    
    def read_data(self):
        """读取LED状态"""
        if not self.initialized or not self.led:
            return None
            
        try:
            # 假设 0 = 开启, 1 = 关闭
            state = self.led.value()
            return {
                "is_on": state == 0  # True表示开启, False表示关闭
            }
        except Exception as e:
            print(f"读取LED状态错误: {e}")
            return None
    
    def execute_command(self, command, value):
        """执行LED控制命令"""
        if not self.initialized or not self.led:
            return {"status": "error", "message": "LED未初始化"}
            
        try:
            if command == "set_state":
                # 设置LED状态 (0 = 开启, 1 = 关闭)
                self.led.value(0 if value else 1)
                return {"status": "success", "is_on": value}
            else:
                return {"status": "error", "message": f"未知命令: {command}"}
        except Exception as e:
            print(f"执行LED命令错误: {e}")
            return {"status": "error", "message": str(e)}